package com.shujia.mr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class wordcount {
    //创建Map类
    public static class MyMap extends Mapper<LongWritable,Text,Text,LongWritable>{
        @Override
        protected void map(LongWritable key, Text info, Context context) throws IOException, InterruptedException {
            String s = info.toString();
            String[] strings = s.split(" ");

            for (String word : strings) {
                context.write(new Text(word),new LongWritable(1L));
            }
        }
    }

    //创建reduce类
    public static class MyReduce extends Reducer<Text,LongWritable,Text,LongWritable>{
        @Override
        protected void reduce(Text word, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            Long sum = 0L;
            for (LongWritable value : values) {
                long num = value.get();
                sum += num;//sum = sum + num
            }
            context.write(word,new LongWritable(sum));
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        //获取hadoop的配置文件
        Configuration conf = new Configuration();
        //创建job任务
        Job job = Job.getInstance(conf, wordcount.class.getSimpleName());
        //获取job运行主类
        job.setJarByClass(wordcount.class);
        //设置数据读取路径
        FileInputFormat.setInputPaths(job,new Path(args[0]));

        //设置map类
        job.setMapperClass(MyMap.class);
        //设置map的输出key和value的类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        //设置reduce类
        job.setReducerClass(MyReduce.class);
        //设置reduce输出的数据类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        //指定输出的HDFS路径
        FileOutputFormat.setOutputPath(job,new Path(args[1]));
        job.waitForCompletion(true);


    }

}
